<?php

class Session {

  private $life_time;
  
  public function __construct($sid=null) {
  
    if(!is_null($sid)){
      session_id($sid);
    }
    // Read the maxlifetime setting from PHP
    $this->life_time = ini_get("session.gc_maxlifetime");
  
    // Register this object as the session handler
    session_set_save_handler( 
      array( &$this, "open" ), 
      array( &$this, "close" ),
      array( &$this, "read" ),
      array( &$this, "write"),
      array( &$this, "destroy"),
      array( &$this, "gc" )
    );
  }
  
  public function open($save_path, $session_name) {
    global $sess_save_path;
    $sess_save_path = $save_path;
    // Don't need to do anything. Just return TRUE.
    return true;
  }
  
  public function close() {
    return true;
  }
  
  public function read($id) {
    // Set empty result
    $data = '';
    // Fetch session data from the selected database
    $db = DB::getDB();
    if ($stmt = $db->prepare("SELECT session_data FROM session
                                  WHERE session_id = ? 
                                    AND expires >= ?")) {
      $time = time();
      $new_id = $id;
      $stmt->bind_param("si", $new_id, $time);
      $stmt->execute();
      $stmt->bind_result($data);
      if(!$stmt->fetch()) {
        $data = '';
      }
      
      $stmt->close();
    }
    
    return $data;
  }
  
  public function write($id, $data) {
    // Build query
    $db = DB::getDB();
    if ($stmt = $db->prepare("REPLACE session 
                                    (session_id, session_data, expires)
                               VALUES
                                    (?,?,?)")) {
      $time = time() + $this->life_time;
      $stmt->bind_param("ssi", $id, $data, $time);
      $stmt->execute();
      $stmt->close();
    }
    
    return TRUE;
  }
  
  public function destroy($id) {
    // Build query
    $db = DB::getDB();
    if ($stmt = $db->prepare("DELETE FROM session WHERE session_id = ?")) {
      $stmt->bind_param("s", $id);
      $stmt->execute();
      $stmt->close();
    }
    return TRUE;
  }
  
  public function gc() {
    // Garbage Collection
    // Build DELETE query.Delete all records who have passed the expiration time
    $db = DB::getDB();
    $db->query('DELETE FROM session WHERE expires < UNIX_TIMESTAMP();');
    // Always return TRUE
    return true;
  }
}
?>